package com.yjymm.edu.interceptor;

import com.yjymm.edu.common.LoginUserContext;
import com.yjymm.edu.mapper.UserMapper;
import com.yjymm.edu.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 判断用户在微信是否登陆
 * @author yjymm
 * @date 2021-01-13 23:00
 */
@Slf4j
public class WxLoginInterceptor implements HandlerInterceptor {

    private UserMapper userMapper;

    public WxLoginInterceptor (UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public static final String WX_LOGIN_HEADER = "Authentication";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (LoginUserContext.getUser() != null) {
            // 验证成功
            return true;
        }
        String openId = request.getHeader(WxLoginInterceptor.WX_LOGIN_HEADER);
        if (openId != null) {
            User user = this.userMapper.selectByOpenId(openId);
            if (user != null) {
                log.info("登陆验证方式：wechat openid");
                LoginUserContext.setUser(user);
            }
        }
        return true;
    }
}
